<template>
  <div class="row q-pa-md">
    <device-map
      class="full-height col"
      :map-id="mapId"
      :center-connected="centerConnected"
      pointShow
      @getPoint="choosePoint"
      v-if="mapId"
    />
    <q-card class="full-height col" :class="ui.cardClass" v-else>
      <div class="absolute-center text-h4">
        {{ $t("BoundManage.未选择地图") }}
      </div>
    </q-card>
    <q-card class="full-height col q-ml-md column" :class="ui.cardClass">
      <q-form @submit="send" class="q-pa-md q-gutter-y-lg">
        <q-select
          :dark="ui.isDark"
          outlined
          v-model="binding.mapPoseId"
          :use-input="!binding.mapPoseId"
          clearable
          :label="$t('BoundManage.选择点位')"
          :options="pointOptions"
          @filter="filterPoint"
          behavior="menu"
          emit-value
          map-options
          option-label="name"
          option-value="id"
        >
          <template v-slot:after>
            <div class="q-gutter-x-lg">
              <q-toggle
                :label="
                  isBinding
                    ? $t('BoundManage.已绑定')
                    : $t('BoundManage.未绑定')
                "
                class="text-subtitle1"
                v-model="isBinding"
              />
              <q-btn
                no-caps
                :label="$t('BoundManage.切换地图')"
                :class="ui.btnClass"
                @click="visible = true"
                icon="map"
              />
            </div>
          </template>
          <template v-slot:no-option>
            <q-item>
              <q-item-section>
                {{
                  isBinding
                    ? $t("BoundManage.暂无已绑定点位")
                    : $t("BoundManage.暂无未绑定点位")
                }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-select
          :dark="ui.isDark"
          outlined
          v-model="binding.postureId"
          :use-input="!binding.postureId"
          clearable
          :label="$t('BoundManage.选择散点') + ' (主-偏拍照侧)'"
          :options="normalOptions"
          @filter="filterNormal"
          behavior="menu"
          emit-value
          map-options
          option-label="name"
          option-value="id"
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section>
                {{ $t("BoundManage.列表为空") }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>

        <q-select
          :dark="ui.isDark"
          outlined
          v-if="!isHiddenSecondaryPosition"
          v-model="binding.vicePostureId"
          :use-input="!binding.vicePostureId"
          clearable
          :label="$t('BoundManage.选择散点') + ' (副)'"
          :options="viceNormalOptions"
          @filter="filterViceNormal"
          behavior="menu"
          emit-value
          map-options
          option-label="name"
          option-value="id"
          :disable="!binding.postureId"
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section>
                {{ $t("BoundManage.列表为空") }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-select
          :dark="ui.isDark"
          outlined
          v-model="binding.storageId"
          :use-input="!binding.storageId"
          clearable
          :label="$t('BoundManage.选择库位')"
          :options="storageOptions"
          @filter="filterStorage"
          behavior="menu"
          emit-value
          map-options
          option-label="name"
          option-value="id"
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section>
                {{ $t("BoundManage.列表为空") }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <div class="full-width row">
          <q-btn
            no-caps
            type="submit"
            :label="$t('BoundManage.绑定')"
            class="full-width"
            :class="ui.btnClass"
            v-if="!isBinding"
            icon="device_hub"
          />
          <template v-else>
            <q-btn
              no-caps
              :label="$t('del')"
              color="red"
              class="col text-space"
              @click="deleteBinding"
              icon="delete"
            />
            <q-btn
              no-caps
              :label="$t('BoundManage.修改')"
              :class="ui.btnClass"
              class="col q-ml-lg"
              type="submit"
              icon="create"
            />
          </template>
        </div>
      </q-form>
      <div class="text-h5 text-center q-mt-lg text-grey q-gutter-y-lg">
        <div class="flex-center items-center">
          {{ $t("BoundManage.上方选择框可进行输入搜索") }}
        </div>
        <div class="flex-center items-center">
          {{ $t("BoundManage.可点击选中左边地图点位进行绑定") }}
        </div>
      </div>
    </q-card>
    <q-dialog v-model="visible">
      <q-card style="min-width: 15rem" :class="ui.cardClass">
        <q-card-section class="q-px-md text-h6">
          {{ $t("BoundManage.选择地图") }}
        </q-card-section>
        <q-separator :dark="ui.isDark" />
        <q-card-section>
          <q-select
            :dark="ui.isDark"
            outlined
            v-model="mapIdStore"
            :use-input="!mapIdStore"
            clearable
            :label="$t('BoundManage.选择地图')"
            :options="mapOptions"
            @filter="filterMap"
            behavior="menu"
            emit-value
            map-options
            option-label="name"
            option-value="id"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section>
                  {{ $t("BoundManage.列表为空") }}
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </q-card-section>
        <q-btn
          no-caps
          :label="$t('BoundManage.确认')"
          :class="ui.btnClass"
          class="full-width"
          @click="chooseMap"
        />
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } from "vue";
import DeviceMap from "components/device/DeviceMap.vue";
import { status } from "src/utils/deviceWs";
import { useUiStore } from "stores/ui";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useFunctionsStore } from "stores/functions";
import { useQuasar } from "quasar";
import { storeToRefs } from "pinia";
import { useI18n } from "vue-i18n";

const t = useI18n().t;
const $q = useQuasar();
const ui = useUiStore();
const { scene,isHiddenSecondaryPosition } = storeToRefs(useFunctionsStore()); //  当前场景
// 计算是否连接到中控
const centerConnected = computed(() => status.value.centerConnected);
// 未绑定的点位状态
const isBinding = ref(false);
// 显示地图选择
const visible = ref(false);
// 计算地图id
const mapId = ref("");
const mapList = ref([]);
const mapOptions = ref([]);
const pointList = ref([]);
const pointOptions = ref([]);
const normalList = ref([]);
const normalOptions = ref([]); // 主散点
const origin = ref([]);
const viceNormalOptions = ref([]); // 副散点
const viceNormalList = ref([]);
const storageList = ref([]);
const storageOptions = ref([]);
const binding = ref({
  mapPoseId: "",
  postureId: "",
  vicePostureId: "",
  storageId: "",
  robotId: "",
});
const mapPoseId = computed(() => binding.value.mapPoseId);
const mapIdStore = ref(""); // 防止选择地图后立马生效
const statusMapID = computed(() => status.value.mapID); // 计算机器人上的mapId是否发生改变
const postureId = computed(() => binding.value.postureId);

onMounted(() => {
  if (status.value.mapID) {
    mapId.value = status.value.mapID;
  } else {
    visible.value = true;
  }
  getAll();
});

watch(visible, (val) => {
  if (val) mapIdStore.value = mapId.value;
});

watch(mapId, () => {
  mapIdStore.value = mapId.value;
  getAll();
  binding.value = {
    mapPoseId: "",
    postureId: "",
    storageId: "",
    vicePostureId: "",
  };
});

watch(statusMapID, (value) => {
  mapId.value = status.value.mapID;
  visible.value = false;
});

// 切换点位后查询出关系表
watch(mapPoseId, (value) => {
  if (!value) {
    binding.value.storageId = "";
    binding.value.postureId = "";
    binding.value.vicePostureId = "";
    binding.value.id = null;
    return;
  }
  if (isBinding.value) {
    api
      .get(useAPIStore().postureUrl + "new/binding/id", {
        params: { mapPoseId: value, robotId: status.value.device },
      })
      .then((rs) => {
        if (rs.data.code !== 200) {
          binding.value.storageId = "";
          binding.value.postureId = "";
          $q.notify({ message: rs.data.message, type: "negative" });
          return;
        }
        binding.value.storageId = rs.data.data.storageId;
        binding.value.postureId = rs.data.data.postureId;
        binding.value.vicePostureId = rs.data.data.vicePostureId;
        binding.value.id = rs.data.data.id;
      });
  }
});
// 监听是否查看未绑定和已绑定点位
watch(isBinding, (value) => {
  if (value) {
    $q.notify({ message: t("BoundManage.切换到已绑定"), type: "positive" });
  } else {
    $q.notify({ message: t("BoundManage.切换到未绑定"), type: "positive" });
  }
  binding.value.storageId = "";
  binding.value.postureId = "";
  binding.value.mapPoseId = "";
  getPoint();
});
// 监听主散点的变化
watch(postureId, (value) => {
  if (!isBinding.value) {
    binding.value.vicePostureId = "";
  }
  viceNormalOptions.value = origin.value.filter((item) => value !== item.id);
  viceNormalList.value = viceNormalOptions.value;
});

// 获取所有需要的数据
function getAll() {
  getMap();
  getPoint();
  getPosture();
  getStorage();
}

// 获取地图列表
function getMap() {
  api.get(useAPIStore().mapUrl + "map/all/simple").then((rs) => {
    mapList.value = rs.data;
    mapOptions.value = mapList.value;
  });
}

// 获取所有规格外的散点
function getPosture() {
  if (!scene.value) return;
  const params = {
    scenario: scene.value.id,
    type: "normal",
  };
  api
    .get(useAPIStore().postureUrl + "new/posture", { params })
    .then((rs) => {
      if (rs.data.code !== 200)
        return $q.notify({
          message: t("BoundManage.姿态列表获取失败"),
          type: "negative",
        });
      normalList.value = rs.data.data.filter(
        (item) => !!item.storage === false
      );
      normalOptions.value = normalList.value;
      origin.value = JSON.parse(JSON.stringify(normalList.value));
    })
    .catch(() => {
      $q.notify({
        message: t("BoundManage.姿态列表获取异常"),
        type: "negative",
      });
    });
}

// 获取库位信息
function getStorage() {
  api
    .get(useAPIStore().postureUrl + "new/storage/scenario", {
      params: { scenario: scene.value.id },
    })
    .then((rs) => {
      if (rs.data.code === 200) {
        storageList.value = rs.data.data.filter(
          (item) => item.onRobot === false
        );
        storageOptions.value = storageList.value;
      } else {
        $q.notify({
          message: t("BoundManage.获取库位失败"),
          type: "negative",
        });
      }
    });
}

// 获取点位
function getPoint() {
  if (!mapId.value) return;
  api
    .get(useAPIStore().postureUrl + "new/binding", {
      params: {
        bound: isBinding.value,
        mapId: mapId.value,
        robotId: status.value.device,
      },
    })
    .then((rs) => {
      if (rs.data.code !== 200)
        return $q.notify({
          message: t("BoundManage.点位列表获取失败"),
          type: "negative",
        });
      pointList.value = rs.data.data;
      pointOptions.value = pointList.value;
    });
}

// 选中点位获取到点位信息
function choosePoint(p) {
  if (p.type !== "storage-catch")
    return $q.notify({ message: t("BoundManage.非库位点"), type: "negative" });
  const list = pointOptions.value.filter((item) => item.id === p.id);
  if (list.length === 0) {
    isBinding.value = !isBinding.value;
    setTimeout(() => {
      binding.value.mapPoseId = p.id;
    }, 800);
  } else {
    binding.value.mapPoseId = p.id;
  }
}

// 绑定点位
function send() {
  // if (!binding.value.postureId)
  //   return $q.notify({
  //     message: t("BoundManage.散点不得为空"),
  //     type: "negative",
  //   });
  if (!binding.value.storageId)
    return $q.notify({
      message: t("BoundManage.库位不得为空"),
      type: "negative",
    });
  $q.dialog({
    dark: ui.isDark,
    title: t("BoundManage.绑定导航点关系"),
    message: t("BoundManage.是否立即绑定关系"),
    ok: t("ok"),
    cancel: t("cancel"),
  }).onOk(() => {
    binding.value.robotId = status.value.device;
    api
      .put(useAPIStore().postureUrl + "new/binding", binding.value)
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({ message: t("BoundManage.绑定成功"), type: "positive" });
          getPoint();
          binding.value.storageId = "";
          binding.value.postureId = "";
          binding.value.mapPoseId = "";
          binding.value.vicePostureId = "";
          binding.value.id = null;
        } else {
          $q.notify({ message: t("BoundManage.绑定失败"), type: "negative" });
        }
      })
      .catch(() => {
        $q.notify({ message: t("RequestError"), type: "negative" });
      });
  });
}

// 删除关系
function deleteBinding() {
  $q.dialog({
    dark: ui.isDark,
    title: t("BoundManage.删除导航点关系"),
    message: t("BoundManage.是否立即删除关系"),
    ok: t("ok"),
    cancel: t("cancel"),
  }).onOk(() => {
    api
      .delete(useAPIStore().postureUrl + "new/binding", {
        params: { id: binding.value.id },
      })
      .then((rs) => {
        if (rs.data.code === 200) {
          $q.notify({ message: t("BoundManage.删除成功"), type: "positive" });
          getPoint();
          binding.value.storageId = "";
          binding.value.postureId = "";
          binding.value.mapPoseId = "";
        } else {
          $q.notify({ message: t("BoundManage.删除失败"), type: "negative" });
        }
      })
      .catch(() => {
        $q.notify({ message: t("RequestError"), type: "negative" });
      });
  });
}

// 选择地图信息
function chooseMap() {
  mapId.value = mapIdStore.value;
  visible.value = false;
}

// 筛选地图信息
function filterMap(val, update) {
  if (val === "") {
    update(() => {
      mapOptions.value = mapList.value;
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    mapOptions.value = mapList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
// 筛选点位信息
function filterPoint(val, update) {
  if (val === "") {
    update(() => {
      pointOptions.value = pointList.value;
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    pointOptions.value = pointList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
// 筛选主散点信息
function filterNormal(val, update) {
  if (val === "") {
    update(() => {
      normalOptions.value = normalList.value;
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    normalOptions.value = normalList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
// 筛选副散点信息
function filterViceNormal(val, update) {
  if (val === "") {
    update(() => {
      viceNormalOptions.value = viceNormalList.value;
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    viceNormalOptions.value = viceNormalList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
// 筛选库位信息
function filterStorage(val, update) {
  if (val === "") {
    update(() => {
      storageOptions.value = storageList.value;
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    storageOptions.value = storageList.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1
    );
  });
}
</script>
